/**
 * The MIT License (MIT)
 * Copyright © 2021 Walkline Wang (https://walkline.wang)
 * https://gitee.com/walkline/online-update-manager
 */	

'use strict'

$(function () {
	app.init()
})

var app = {
	controls: {
		text_signin_username: $('#text_signin_username'),
		text_signin_password: $('#text_signin_password'),
	
		button_signin: $('#button_signin')
	},

	init: function () {
		this._bind_signin_click_event()
		this._setup_toastr()
	},

	_bind_signin_click_event: function () {
		this.controls.button_signin.on('click', () => {
			if (this._validate_signin_value()) {
				$.post(CONST.UPDATE_API_URI + CONST.COMMANDS.SIGNIN_USER, {
					username: app.controls.text_signin_username.val(),
					password: $.md5(app.controls.text_signin_password.val()),
				}, function (result) {
					if (!result.error_code) {
						location.href = './'
					} else {
						toastr.warning('错误: ' + result.error_msg)
					}
				})
			}
		})
	},

	_setup_toastr: function () {
		toastr.options.positionClass = 'toast-top-right'
		toastr.options.timeOut = 3000
	},

	_validate_signin_value: function () {
		let result = true
		const username = this.controls.text_signin_username,
			password = this.controls.text_signin_password

		if (username.val().trim() === '') {
			toastr.warning('错误: 用户名不能为空')

			username.focus()
			result = false
		} else if (password.val().trim() === '') {
			toastr.warning('错误: 密码不能为空')

			password.focus()
			result = false
		}

		return result
	}
}